package org.bp.util;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;

/**
 * @author baiping
 * @version 1.0
 * @date 2017/9/6
 */
public class StreamUtils {
	/**
	 * 将offset~offset+len输出流复制到输入流
	 * 
	 * @param input
	 * @param output
	 * @param offset
	 * @param len
	 * @return
	 * @throws IOException
	 */
	public static long copyStream(InputStream input, OutputStream output, int offset, int len) throws IOException {
		byte[] buffer = new byte[4096];
		long count = 0L;
		int n1;
		for (; -1 != (n1 = input.read(buffer, offset, len)); count += (long) n1) {
			output.write(buffer, offset, len);
		}

		return count;
	}

	/**
	 * 复制流
	 * 
	 * @param input
	 * @param output
	 * @return
	 * @throws IOException
	 */
	public static long copyStream(InputStream input, OutputStream output) throws IOException {
		byte[] buffer = new byte[4096];
		long count = 0L;

		int n1;
		for (; -1 != (n1 = input.read(buffer)); count += (long) n1) {
			output.write(buffer, 0, n1);
		}

		return count;
	}

	/**
	 * 关闭流
	 * 
	 * @param closeables
	 */
	public static void close(Closeable... closeables) {
		if (ObjectUtils.isNotNull(closeables)) {
			for (Closeable closeable : closeables) {
				if (closeable != null) {
					try {
						if (closeable instanceof OutputStream) {
							((OutputStream) closeable).flush();
						}
						if (closeable instanceof Writer) {
							((Writer) closeable).flush();
						}
						closeable.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 关闭
	 * 
	 * @param closeables
	 */
	public static void close(AutoCloseable... closeables) {
		if (ObjectUtils.isNotNull(closeables)) {
			for (AutoCloseable closeable : closeables) {
				if (closeable != null) {
					try {
						closeable.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
